package com.link.base.tencent.corpwx.usertag.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.usertag.dao.mybatis.mapper.UserTagMapper;
import com.link.base.tencent.corpwx.usertag.model.UserTag;
import com.link.base.tencent.corpwx.usertag.model.UserTagItem;
import com.link.base.tencent.corpwx.usertag.util.UserTagUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 成员标签 
 *
 * @author 欧阳振强
 * @date 2020-01-06 10:35:58.0
 */
@Service
public class UserTagServiceImpl extends BasicServiceImpl<UserTag> implements UserTagService {
    /**标签状态-等待添加*/
    private static final String TAG_STATUS_WAIT_ADD = "waitAdd";
    /**标签状态-已添加*/
    private static final String TAG_STATUS_ALREADY_ADD = "alreadyAdd";
    /**标签状态-等待删除*/
    private static final String TAG_STATUS_WAIT_DEL = "waitDel";

    @Resource
    private UserTagMapper userTagMapper;
    @Resource
    private UserTagItemService userTagItemService;
    @Resource
    private AgentService agentService;
    @Resource
    private KeyGenerateService keyGenerateService;
    
    @Override
    public BasicMapper<UserTag> getBasicMapper() {
        return userTagMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncAllUserTagFromWx() throws Exception {
        // 获取所有标签
        JSONObject tagData = UserTagUtil.listTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID));
        JSONArray tagArray = tagData.getJSONArray("taglist");
        for (int i = 0; i < tagArray.size(); i++) {
            JSONObject tagObj = tagArray.getJSONObject(i);
            // 拉取标签下成员
            JSONObject tagUserData = UserTagUtil.getTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID),
                    tagObj.getString("tagid"));
            JSONArray tagUserArray = tagUserData.getJSONArray("userlist");
            // 判断标签是否存在
            UserTag userTagParam = new UserTag();
            userTagParam.setTagId(tagObj.getString("tagid"));
            UserTag userTag = userTagMapper.getUserTagByTagId(userTagParam);
            if (userTag == null) {
                // 不存在则直接新建标签
                Long tagCrmId = keyGenerateService.keyGenerate();
                userTagParam.setTagName(tagObj.getString("tagname"));
                userTagParam.setId(tagCrmId);
                userTagMapper.insert(userTagParam);
                for (int j = 0; j < tagUserArray.size(); j++) {
                    // 新建标签成员关系
                    JSONObject tagUserObj = tagUserArray.getJSONObject(j);
                    UserTagItem userTagItem = new UserTagItem();
                    userTagItem.setId(keyGenerateService.keyGenerate());
                    userTagItem.setHeadId(tagCrmId);
                    userTagItem.setUserId(tagUserObj.getString("userid"));
                    userTagItem.setStatus(TAG_STATUS_ALREADY_ADD);
                    userTagItemService.insert(userTagItem);
                }
            } else {
                // 存在则更新标签名字
                userTag.setTagName(tagObj.getString("tagname"));
                userTagMapper.update(userTag);
                List<String> tagUserList = new ArrayList<>();
                // 构造企业微信标签成员字符串列表
                for (int j = 0; j < tagUserArray.size(); j++) {
                    tagUserList.add(tagUserArray.getJSONObject(j).getString("userid"));
                }
                // 查询CRM端标签下成员列表
                List<UserTagItem> crmUserTagItemList = userTagItemService.getUserTagItemListByTag(userTag);
                // 完全同步标签成员关系，即企业微信有+CRM无=新增；企业微信无+CRM有=删除；企业微信有+CRM有=略过
                List<UserTagItem> opUserTagItemList = userTagItemService.opUserTagItemList(tagUserList, crmUserTagItemList);
                for (UserTagItem item: opUserTagItemList) {
                    String status = item.getStatus();
                    if (TAG_STATUS_WAIT_ADD.equals(status)) {
                        // 新建标签成员关系
                        item.setId(keyGenerateService.keyGenerate());
                        item.setHeadId(userTag.getId());
                        item.setStatus(TAG_STATUS_ALREADY_ADD);
                        userTagItemService.insert(item);
                    } else if (TAG_STATUS_WAIT_DEL.equals(status)) {
                        userTagItemService.deleteById(item);
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncSingleUserTagToWx(UserTag userTag) throws Exception {
        String tagId = userTag.getTagId();
        if (StringUtils.isBlank(tagId)) {
            // 标签尚未同步，先做同步操作
            JSONObject resultObj = UserTagUtil.createTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID),
                    userTag.getTagName());
            tagId = resultObj.getString("tagid");
            userTag.setTagId(tagId);
            userTagMapper.update(userTag);
        } else {
            // 标签存在则更新
            UserTagUtil.updateTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), tagId, userTag.getTagName());
        }
        // 查询CRM端标签下成员列表
        List<UserTagItem> crmUserTagItemList = userTagItemService.getUserTagItemListByTag(userTag);
        // 筛选出待添加和待删除标签成员
        List<UserTagItem> addUserTagItemList = new ArrayList<>();
        List<UserTagItem> delUserTagItemList = new ArrayList<>();
        for (UserTagItem item: crmUserTagItemList) {
            String status = item.getStatus();
            if (TAG_STATUS_WAIT_ADD.equals(status)) {
                addUserTagItemList.add(item);
            } else if (TAG_STATUS_WAIT_DEL.equals(status)) {
                delUserTagItemList.add(item);
            }
        }
        // 用于控制接口调用对于ID数量的限制为1000
        int userIds = 0;
        List<String> userIdList = new ArrayList<>();
        // 删除标签成员
        for (UserTagItem item: delUserTagItemList) {
            userIdList.add(item.getUserId());
            userIds++;
            if (userIds == 1000) {
                UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "del", tagId, userIdList, null);
                userIds = 0;
                userIdList.clear();
            }
        }
        if (userIdList.size() > 0) {
            UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "del", tagId, userIdList, null);
        }
        // 添加标签成员
        for (UserTagItem item: addUserTagItemList) {
            userIdList.add(item.getUserId());
            userIds++;
            if (userIds == 1000) {
                UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "add", tagId, userIdList, null);
                userIds = 0;
                userIdList.clear();
            }
        }
        if (userIdList.size() > 0) {
            UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "add", tagId, userIdList, null);
            userIds = 0;
            userIdList.clear();
        }
        // 回写标签成员状态为已添加
        for (UserTagItem item: addUserTagItemList) {
            item.setStatus(TAG_STATUS_ALREADY_ADD);
            userTagItemService.update(item);
        }
    }

    @Override
    public void deleteUserTag(UserTag userTag) throws Exception {
        String tagId = userTag.getTagId();
        if (StringUtils.isNotBlank(tagId)) {
            // 删除企业微信端标签，企业微信端标签下成员目前删除标签后即失效，此处不单独再调用接口进行删除
            UserTagUtil.deleteTag(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), tagId);
        }
        // 删除CRM标签
        userTagMapper.deleteById(userTag);
        // 删除CRM标签下成员
        userTagItemService.delUserTagByHeadId(userTag);
    }
}